package 二叉树;

import java.util.HashMap;
import java.util.Map;

/**
 * 这道题是要通过前序和中序来还原原来的二叉树 如果只是自己画出来还是蛮容易的
 * 但是思路是要用递归来解决的话 其实就要考虑递归的是位置
 * 所以下次不懂自己画个图 配着代码看就懂了
 * 题目地址：https://leetcode-cn.com/problems/zhong-jian-er-cha-shu-lcof/submissions/
 */
public class 重建二叉树 {
    public class TreeNode {
      int val;
      TreeNode left;
      TreeNode right;
      TreeNode(int x) { val = x; }
  }
    private Map<Integer, Integer> indexMap;
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        int n = preorder.length;
        indexMap = new HashMap<Integer, Integer>();
        for (int i = 0; i < n; i++) {
            indexMap.put(inorder[i],i);
        }
        return myBuildTree(preorder,inorder,0,n-1,0,n-1);

    }

    private TreeNode myBuildTree(int[] preorder, int[] inorder, int pre_left, int pre_right, int in_left, int in_right) {
        if (pre_left>pre_right){
            return null;
        }
        //前序第一个就是根节点
        int pre_root = pre_left;
        //在中序遍历中定位根节点
        int in_root = indexMap.get(preorder[pre_root]);
        //根节点先建立起来
        TreeNode root = new TreeNode(preorder[pre_root]);
        //得到左节点的节点个数
        int left_size_subtree = in_root-in_left;
        //递归构造左子树 并连接到根节点
        root.left = myBuildTree(preorder,inorder,pre_left+1,pre_left+left_size_subtree,in_left,in_root-1);
        root.right = myBuildTree(preorder,inorder,pre_left+left_size_subtree+1,pre_right,in_root+1,in_right);
        return root;
    }
}
